using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using HtmlAgilityPack;


public class NetworkRequest : MonoBehaviour 
{
	public Text inputTxtName;
	public Text seekCount;
	public Transform cellparent;
	public Transform poolManager;

	private string url = "https://www.qidian.com/search?kw=";
 
	void Start(){
       
    }

	public void RequestThebook()
	{
	    StartCoroutine(Seekname());
	}

	IEnumerator Seekname()
	{
		WWW www = new WWW (url+inputTxtName.text);
		yield return www;
		if(string.IsNullOrEmpty(www.error))
		{
            Debug.Log (www.text);
		    DecodeHtml (www.text);
		}
	}

	private void DecodeHtml(string sr)
	{
		HtmlDocument doc = new HtmlDocument ();
		doc.LoadHtml (sr);
		HtmlNodeCollection list=doc.DocumentNode.SelectNodes(".//h4/a[1]");
		//Debug.Log (list.Count);
		seekCount.text="总计搜索结果 ：        "+list.Count+"个";
		if(list!=null)
		{
			foreach(HtmlNode h in list)
			{
				//HtmlAttribute att = h.Attributes ["href"];
				//Debug.Log (h.InnerText);
                CreateCell (h.InnerText.Trim());
			}
		}
		else
		{
			Debug.Log ("Error");
		}
	}

	private void CreateCell(string txtName)
	{
		GameObject cell;
		if(poolManager.childCount>0)
		{
			cell = poolManager.GetChild (0).gameObject;
			cell.SetActive (true);
		}
		else
		{
			GameObject cellPrefab = Resources.Load<GameObject> ("SearchCell");
			cell =  Instantiate (cellPrefab) as GameObject;
		}

		cell.transform.SetParent (cellparent);
		cell.GetComponent<RectTransform> ().localScale = Vector3.one;
		cell.transform.GetComponentInChildren<Text> ().text = txtName;
	}





}
